# -*- coding: utf-8 -*-
__author__ = 'alex'


from xml.sax import handler
from page_entity import PageEntity
from db_routine import *
from WikiAttibParser import WikiAttribParser


class WikiPageParser(handler.ContentHandler):
    def __init__(self, dbWriter):
        handler.ContentHandler.__init__(self)
        self._lastElement = ''
        self._currentPage = PageEntity()
        self._dbWriter = dbWriter
        self._attribParser = WikiAttribParser(dbWriter.getInfPageDescription())
        self.pageCounter = 0

    def startDocument(self):
        pass
        #print 'start'

    def endDocument(self):
        pass


    def startElement(self, name, attrs):
        self._lastElement = name


    def endElement(self, name):
        #print "end", name
        self._lastElement = u''

        if name == u'id' and self._currentPage._isChecked == False:
            self._currentPage._isInteresting = \
                    self._attribParser.checkForInteresting(self._currentPage._id)
            self._currentPage._isChecked = True

        if name == u'page':
            if self._currentPage._isInteresting:
                infobox = self._attribParser.getNewAttrib(self._currentPage)
                if infobox is not None:
                    self._dbWriter.write(infobox)
                
            self._currentPage = PageEntity()
                
            self.pageCounter += 1
            if self.pageCounter % 1000 == 0:
                print self.pageCounter
                
            #print "infobox id =", infobox[0]
            #for i in infobox[1]:
            #    print i



    def characters(self, content):
        if self._currentPage._isInteresting:
            self._currentPage.add(self._lastElement, content)


  